import {Component, OnInit} from '@angular/core';
import {BusinessCircleService} from '../../../business-circle/business-circle.service';
import tinymce from 'tinymce';
import 'tinymce/icons/default/icons.min';
import {ActivatedRoute} from '@angular/router';
import {BusinessStrategyService} from '../business-strategy.service';
import {NzMessageService} from 'ng-zorro-antd/message';

@Component({
  selector: 'app-article-add',
  templateUrl: './article-add.component.html',
  styleUrls: ['./article-add.component.scss']
})
export class ArticleAddComponent implements OnInit {

  // 编辑器配置
  editorConfig: any = {
    base_url: '/tinymce',
    branding: false,
    inline_boundaries: false,
    content_css: '/assets/css/tinymce-style.css',
    content_style: 'img {max-width:100%;} body {margin: 10px;}',
    language: 'zh_CN',
    language_url: '/tinymce/lang/zh_CN.js',
    plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave bdmap indent2em autoresize formatpainter axupimgs',
    toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
    styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
    table image charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight formatpainter axupimgs',
    height: 450, // 编辑器高度
    min_height: 400,
    max_height: 800,
    placeholder: '请输入内容...',
    fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
    font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
    // automatic_uploads: false,
    image_dimensions: false,
    images_upload_handler: (blobInfo: any, succFun: any, failFun: any) => {
      this.businessCircleService.uploadFileData(blobInfo.blob()).then((res: any) => {
        if (res.code === 0 && res.data) {
          succFun(res.data);
        } else {
          failFun(res.message || '图片上传失败');
        }
      }).catch((error: any) => {
        failFun(error);
      });
    },
  };
  formData = {
    id: '',
    title: '',
    image: '',
    subTitle: '',
    category: '',
    content: '',
    status: 3,
  };

  categoryOptions = [];

  constructor(
    private businessCircleService: BusinessCircleService,
    private activatedRoute: ActivatedRoute,
    private bSService: BusinessStrategyService,
    private nzMessageService: NzMessageService
  ) {
  }

  ngOnInit(): void {
    let data = this.activatedRoute.snapshot.queryParams?.data;
    if (data) {
      data = JSON.parse(data);
      this.formData = {
        id: data.id,
        title: data.title,
        image: data.picture,
        subTitle: data.subtitleName,
        category: data.eid,
        content: data.content,
        status: data.status,
      };
    }
    const editor: any = tinymce.get('editorID');
    this.bSService.getArticleCategory().then((res: any) => {
      if (res.code === 0) {
        this.categoryOptions = res.data.records;
      }
    });
  }

  save() {
    console.log(this.formData);
    if (!this.formData.title) {
      this.nzMessageService.error('请输入文章标题');
      return;
    }
    if (!this.formData.subTitle) {
      this.nzMessageService.error('请输入副标题');
      return;
    }
    if (!this.formData.category) {
      this.nzMessageService.error('请选择文章分类');
      return;
    }
    if (!this.formData.image) {
      this.nzMessageService.error('请选择主图');
      return;
    }
    if (this.formData.id === '') {
      this.bSService.addArticle({
        title: this.formData.title,
        picture: this.formData.image,
        subtitleName: this.formData.subTitle,
        eId: this.formData.category,
        content: this.formData.content,
        status: this.formData.status,
      }).then((res: any) => {
        if (res.code === 0) {
          this.nzMessageService.success('操作成功');
          window.history.back();
        } else {
          this.nzMessageService.error(res.message);
        }
      });
    } else {
      this.bSService.editArticle({
        id: this.formData.id,
        title: this.formData.title,
        picture: this.formData.image,
        subtitleName: this.formData.subTitle,
        eId: this.formData.category,
        content: this.formData.content,
        status: this.formData.status,
      }).then((res: any) => {
        if (res.code === 0) {
          this.nzMessageService.success('操作成功');
          window.history.back();
        } else {
          this.nzMessageService.error(res.message);
        }
      });
    }
  }

  preview() {
    tinymce.get('editorID').execCommand('mcePreview');
  }
}
